#include <iostream>
#include <unistd.h>
#include <pthread.h>
using namespace std;
int cnt=0;
#define NUM 5
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;//结构体
pthread_cond_t cond=PTHREAD_COND_INITIALIZER;//条件变量


void* Count(void* args)
{
    pthread_detach(pthread_self());//区分detach和cancel
    uint64_t number = (uint64_t)(args);
    cout<<"pthread: "<<number<<" , create success"<<endl;
    while(true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond,&mutex);//---------同步?为什么在这里
        //1.线程拿到锁后,pthread_cond_wait让线程等待,并且释放它的锁
        //  所以多个线程都可以到pthread_cond_wait这一步
        cout<<"pthread: "<<number<<" , cnt:"<<cnt++<<endl;
        pthread_mutex_unlock(&mutex);
    }
}
int main()
{
    
    for(uint64_t i=0;i<NUM;i++)
    {
        pthread_t tid;
        pthread_create(&tid,nullptr,Count,(void*)i);
        //注意细节: 传i,使用的时候直接强转int
        //如果&i,多线程有并发问题,多线程共享了同一变量
        //i是传拷贝
        usleep(1000);
    }
    sleep(3);
    cout<<"main thread ctrl begin: "<<endl;
    while(true)
    {
        sleep(1);
        //pthread_cond_signal(&cond);//唤醒在cond下等待的一个线程,默认是第一个
        //cout<<"signal one thread..."<<endl;
        pthread_cond_broadcast(&cond);
        cout<<"signal all threads..."<<endl;

    }                                                       
    return 0;
}